package com.example.myapplication.module1.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.ConstantsData
import com.example.myapplication.R
import com.example.myapplication.databinding.ActivityPersonalScheduleBinding
import com.example.myapplication.entity.ItemBean
import com.example.myapplication.entity.ScheduleBean
import com.example.myapplication.module1.adapter.ScheduleAdapter
import com.example.myapplication.module1.presenter.PersonalSchedulePresenter
import com.example.myapplication.soaprequest.SoapEnvelop
import com.example.myapplication.soaprequest.request.DeldataRequest
import com.example.myapplication.soaprequest.request.RcpromptListRequest
import com.example.myapplication.soaprequest.request.SoapRequestBody
import com.example.myapplication.widget.CustomerToolbar
import com.example.mylibrary.adapter.BaseRecyclerAdapter
import com.example.mylibrary.base.BaseMvpActivity
import com.example.mylibrary.utils.GsonUtil
import com.example.mylibrary.utils.UiTools
import com.google.gson.reflect.TypeToken
import com.lxj.xpopup.impl.LoadingPopupView
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 * 个人日程
 */
class PersonalScheduleActivity :
    BaseMvpActivity<PersonalScheduleActivity, PersonalSchedulePresenter, ActivityPersonalScheduleBinding>() {
    private val rcpromptListRequest = RcpromptListRequest()
    private val deldataRequest = DeldataRequest()
    private val soapRequestBody = SoapRequestBody()
    private val soapEnvelop = SoapEnvelop()
    lateinit var loadPopup: LoadingPopupView
    private var curPage = 1
    private val tempScheduleBeanList = mutableListOf<ScheduleBean>()

    override fun getPresenter(): PersonalSchedulePresenter {
        return PersonalSchedulePresenter()
    }

    override fun getBinding(): ActivityPersonalScheduleBinding {
        return ActivityPersonalScheduleBinding.inflate(layoutInflater)
    }

    private val scheduleAdapter: ScheduleAdapter by lazy {
        ScheduleAdapter(this)
    }

    override fun initData() {
        getSchedule()
    }

    // 个人日程访问
    private fun getSchedule() {
        if (curPage == 1) {
            tempScheduleBeanList.clear()
        }
        rcpromptListRequest.curpage = "$curPage"
        soapRequestBody.value = rcpromptListRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.getSchedule(soapEnvelop)
    }

    override fun initView() {
        viewBinding.ivAdd.setOnClickListener(this)
        viewBinding.ivDelete.setOnClickListener(this)
        viewBinding.list.rvList.addItemDecoration(
            DividerItemDecoration(
                this,
                RecyclerView.VERTICAL
            )
        )
        viewBinding.list.rvList.adapter = scheduleAdapter
        scheduleAdapter.clickListener = object : BaseRecyclerAdapter.ClickListener {
            override fun clickListener(position: Int, view: View?) {
                val bundle = Bundle()
                val scheduleBeanList = scheduleAdapter.scheduleBeanList
                if (!scheduleBeanList.isNullOrEmpty()) {
                    val scheduleBean = scheduleBeanList[position]
                    bundle.putParcelable("scheduleBean", scheduleBean)
                    startNextActivityForResult(
                        this@PersonalScheduleActivity,
                        ConstantsData.SCHEDULE_REQUEST,
                        bundle,
                        ScheduleDetailActivity::class.java
                    )
                }
            }

            override fun longClickListener(position: Int, view: View?): Boolean {
                return false
            }

        }

        loadPopup = builder.asLoading("加载中...")
        val itemInfo = bundleExtra?.getParcelable<ItemBean>("itemInfo")
        viewBinding.clToolbar.setTitle(itemInfo?.itemName)
        viewBinding.clToolbar.clickListener = object : CustomerToolbar.ClickListener {
            override fun onBackListener() {
                finish()
            }

            override fun onRightListener() {

            }
        }

        viewBinding.list.srlRefresh.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                curPage = 1
                getSchedule()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                curPage += 1
                getSchedule()
            }
        })

    }

    private val stringBuffer = StringBuffer()
    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.ivAdd -> {
                startNextActivityForResult(
                    this@PersonalScheduleActivity,
                    ConstantsData.SCHEDULE_REQUEST,
                    null,
                    ScheduleDetailActivity::class.java
                )
            }
            R.id.ivDelete -> {
                val scheduleBeanList = scheduleAdapter.scheduleBeanList
                if (!scheduleBeanList.isNullOrEmpty()) {
                    stringBuffer.setLength(0)
                    for (scheduleBean in scheduleBeanList) {
                        if (scheduleBean.isCheck) {
                            stringBuffer.append("${scheduleBean.id},")
                        }
                    }
                }
                delSchedule()
            }
        }
    }

    // 删除个人日程
    private fun delSchedule() {
        if (curPage == 1) {
            tempScheduleBeanList.clear()
        }
        deldataRequest.ids = stringBuffer.toString()
        deldataRequest.itemtype = "GRRC"
        soapRequestBody.value = deldataRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.delSchedule(soapEnvelop)
    }

    fun setScheduleResult(result: String) {
        val scheduleBeanList = GsonUtil.fromJson<MutableList<ScheduleBean>>(
            result,
            object : TypeToken<MutableList<ScheduleBean>>() {}.type
        )
        if (scheduleBeanList.isNullOrEmpty()) {
            viewBinding.list.srlRefresh.setEnableLoadMore(false)
            UiTools.showToast(R.string.noMoreInfo)
        } else {
            viewBinding.list.srlRefresh.setEnableLoadMore(true)
            tempScheduleBeanList.addAll(scheduleBeanList)
        }
        scheduleAdapter.scheduleBeanList = tempScheduleBeanList
        if (tempScheduleBeanList.isNotEmpty()) {
            viewBinding.noData.clNoData.visibility = View.GONE
        } else {
            viewBinding.noData.clNoData.visibility = View.VISIBLE
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                ConstantsData.SCHEDULE_REQUEST -> {
                    curPage = 1
                    getSchedule()
                }
                else -> {
                }
            }
        }
    }

    fun showLoad() {
        if (!viewBinding.list.srlRefresh.isRefreshing && !viewBinding.list.srlRefresh.isLoading) {
            loadPopup.show()
        }
    }

    fun dismissLoad() {
        loadPopup.dismiss()
        if (viewBinding.list.srlRefresh.isRefreshing || viewBinding.list.srlRefresh.isLoading) {
            viewBinding.list.srlRefresh.finishRefresh()
            viewBinding.list.srlRefresh.finishLoadMore()
        }
    }

    fun delScheduleResult(result: String) {
        UiTools.showToast("删除成功")
        curPage = 1
        getSchedule()
    }

}
